<template>
  <div class="ui-toolbar" :class="['is-' + align]">
    <slot />
    <div
      v-for="(item, index) in showItems"
      :key="`item-${index}`"
      class="ui-toolbar__item"
      :class="{'is-divided': item.props.divided}"
    >
      <template v-if="!item.props.divided">
        <component :is="handleRenderItem(item)" :data-key="item.info.count" />
      </template>
    </div>
  </div>
</template>
<script>
export default {
  name: 'UiToolbar',
  provide() {
    return {
      UiToolbar: this
    }
  },
  props: {
    align: {
      type: String,
      default: 'left',
      validator(value) {
        return ['left', 'center', 'right'].includes(value)
      }
    },
    bindClose: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      items: []
    }
  },
  computed: {
    showItems () {
      return this.items.filter(v => v.props.show !== false)
    }
  },
  methods: {
    handleRenderItem(item) {
      return {
        functional: true,
        render: (h, c) => {
          return item.render(h, c)
        }
      }
    },
    addItem(item) {
      if (!item || !item.id) {
        return
      }
      let index = -1
      this.items.some((v, i) => {
        if (v.id === item.id) {
          index = i
          return true
        }
      })
      if (index >= 0) {
        this.items.splice(index, 1, item)
      } else {
        this.items.push(item)
      }
    },
    removeItem(id) {
      this.items = this.items.filter(v => v.id !== id)
    }
  }
}
</script>
<style lang="less">
.ui-toolbar{
  display: flex;
  flex-direction: row;
  align-items: center;
  &.is-center {
    justify-content: center;
  }
  &.is-right {
    justify-content: flex-end;
  }
}
.ui-toolbar__item{
  margin-left: 12px;
  &.is-divided {
    width: 1px;
    height: 18px;
    background-color: rgba(0,0,0,.08);
  }
}
.ui-toolbar__item:first-child{
  margin-left: 0;
}
</style>
